package cn.lyh97.estore.easystoremanager.Activities;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieEntry;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.lyh97.estore.easystoremanager.Classes.GoodsAdapter;
import cn.lyh97.estore.easystoremanager.Classes.GoodsItem;
import cn.lyh97.estore.easystoremanager.Classes.SqlHelper;
import cn.lyh97.estore.easystoremanager.Fragments.ChartFragment;
import cn.lyh97.estore.easystoremanager.Fragments.GoodsFragment;
import cn.lyh97.estore.easystoremanager.Fragments.ItemFragment;
import cn.lyh97.estore.easystoremanager.Fragments.ScanFragment;
import cn.lyh97.estore.easystoremanager.R;
import cn.lyh97.estore.easystoremanager.ZXing.CaptureActivity;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    public static Fragment nowFragment;
    public static FragmentManager fragmentManager;

    private GoodsFragment goodsFragment;
    private ChartFragment chartFragment;
    private ScanFragment scanFragment;
    public static ItemFragment itemFragment;

    private ImageView mainBtmGoodsImg;
    private ImageView mainBtmChartImg;
    private ImageView mainBtmScanImg;

    private TextView mainBtmGoodsTxt;
    private TextView mainBtmChartTxt;
    private TextView mainBtmScanTxt;

    private SqlHelper sqlHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_activity);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                MainActivity.this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(MainActivity.this);


        fragmentManager = getSupportFragmentManager();
        init();
       /* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });*/

    }

    //<editor-fold 系统函数>
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else if (itemFragment.isVisible()) {
            showFragment(goodsFragment);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        // getMenuInflater().inflate(R.menu.main, menu);
        super.onCreateOptionsMenu(menu);
        int group1 = 1;
        int group2 = 2;
        menu.add(group1, 1, 1, "item1");
        menu.add(group1, 2, 2, "item2");
        menu.add(group2, 3, 3, "item3");
        menu.add(group2, 4, 4, "item4");
        menu.removeGroup(group1);
        menu.setGroupVisible(group2, true);
        menu.setGroupEnabled(group2, true);
        menu.setGroupCheckable(group2, true, true);
        return true;
    }

   /* @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }*/

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        // if (id == R.id.action_settings) {
        // return true;
        //}

        switch (id) {

            case 1:
                showAlert((String) item.getTitle(), null);
                return true;
            case 2:
                showAlert((String) item.getTitle(), null);
                return true;
            case 3:
                showAlert((String) item.getTitle(), null);
                return true;
            case 4:
                showAlert((String) item.getTitle(), null);
                return true;

        }
        return false;

    }

   /* @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Toast.makeText(this,"setting",Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }*/
//</editor-fold>

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.navMenuSettingBtn){
            Intent intent = new Intent(this,SettingsActivity.class);
            startActivity(intent);
        }
        if(id == R.id.navMenuAttachmentBtn){
            Intent intent = new Intent(this,AboutUsActivity.class);
            startActivity(intent);
        }
/*
        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }*/

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void init() {
        sqlHelper = new SqlHelper(this);

        mainBtmGoodsImg = (ImageView) findViewById(R.id.mainBtmGoodsImg);
        mainBtmGoodsTxt = (TextView) findViewById(R.id.mainBtmGoodsTxt);
        mainBtmChartImg = (ImageView) findViewById(R.id.mainBtmChartImg);
        mainBtmChartTxt = (TextView) findViewById(R.id.mainBtmChartTxt);
        mainBtmScanImg = (ImageView) findViewById(R.id.mainBtmScanImg);
        mainBtmScanTxt = (TextView) findViewById(R.id.mainBtmScanTxt);

        mainBtmGoodsImg.setImageResource(R.drawable.goods_blue);
        mainBtmGoodsTxt.setTextColor(ContextCompat.getColor(this, R.color.btm_on));

        FragmentTransaction transaction = fragmentManager.beginTransaction();
        goodsFragment = new GoodsFragment();
        chartFragment = new ChartFragment();
        scanFragment = new ScanFragment();
        itemFragment = new ItemFragment();

        transaction.add(R.id.main_content_framelayout, goodsFragment);
        transaction.add(R.id.main_content_framelayout, chartFragment);
        transaction.add(R.id.main_content_framelayout, scanFragment);
        transaction.add(R.id.main_content_framelayout, itemFragment);

        transaction.show(goodsFragment);
        transaction.hide(chartFragment);
        transaction.hide(scanFragment);
        transaction.hide(itemFragment);

        nowFragment = goodsFragment;
        transaction.commit();
    }

    public void onClickBottom(View view) {
        clearBottomColor();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.hide(nowFragment);
        int id = view.getId();
        switch (id) {
            case R.id.main_btm_goods_v: {
                mainBtmGoodsImg.setImageResource(R.drawable.goods_blue);
                mainBtmGoodsTxt.setTextColor(ContextCompat.getColor(this, R.color.btm_on));
                transaction.show(goodsFragment);
                nowFragment = goodsFragment;
                transaction.commit();
                updateGoodsListView();
            }
            break;
            case R.id.main_btm_chart_v: {
                mainBtmChartImg.setImageResource(R.drawable.chart_blue);
                mainBtmChartTxt.setTextColor(ContextCompat.getColor(this, R.color.btm_on));
                transaction.show(chartFragment);
                nowFragment = chartFragment;
                transaction.commit();
            }
            break;
            case R.id.main_btm_scan_v: {
                mainBtmScanImg.setImageResource(R.drawable.scan_blue);
                mainBtmScanTxt.setTextColor(ContextCompat.getColor(this, R.color.btm_on));
                transaction.show(scanFragment);
                nowFragment = scanFragment;
                transaction.commit();
            }
            break;
            default:
                break;
        }
    }

    public void onClickGoodsFragment(View view) {
        int id = view.getId();
        switch (id) {
            case 1: {

            }
            break;
            default:
                break;
        }
    }

    public void onClickChartFragment(View view) {
        int id = view.getId();

        List<GoodsItem> goodsList = sqlHelper.getAllGoodsItem();
        ArrayList<String> listStr = new ArrayList<String>();

        for (int i = 0; i < goodsList.size(); i++) {
            String tag = goodsList.get(i).getTag();
            if (!listStr.contains(tag)) {
                listStr.add(tag);
            }
        }

        int tagsNum = listStr.size();

//        List<GoodsItem>[] goodsTagList = new List[listStr.size()];
//
//        for (int j = 0; j < tagsNum; j++) {
//            goodsTagList[j] = sqlHelper.getGoodsItemsByTag(listStr.get(j));
//        }

        switch (id) {
            case R.id.chartFragmentStockBtn: {

                ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
                Float[] num = new Float[tagsNum];
                for (int i = 0; i < tagsNum; i++) {
                    num[i] = 0f;
                }

                //对Tag[i] 进行循环
                for (int i = 0; i < tagsNum; i++) {

                    //对goodsItem 进行循环
                    for (GoodsItem item: sqlHelper.getGoodsItemsByTag(listStr.get(i)) ) {
                        num[i] += item.getNum();
                    }
                    entries.add(new PieEntry(num[i], listStr.get(i) ));
                }

                PieChart chart = (PieChart) chartFragment.getView().findViewById(R.id.chartFragmentChartView);
                ChartFragment.setPieData(chart,entries);
                ChartFragment.initChart(chart,"库存数量比例图");
            }
            break;
            case R.id.chartFragmentProfitBtn: {
                ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
                int historyNum = 0;
                int sellNumInt = 0;
                Float[] sellNum = new Float[tagsNum];

                for (int i = 0; i < tagsNum; i++) {
                    sellNum[i] = 0f;
                }

                //对Tag[i] 进行循环
                for (int i = 0; i < tagsNum; i++) {

                    //对goodsItem 进行循环
                    for (GoodsItem item: sqlHelper.getGoodsItemsByTag(listStr.get(i)) ) {
                        historyNum = getCurrentHistoryNum(item);
                        sellNumInt = historyNum - item.getNum();
                        sellNum[i] += sellNumInt * item.getProfit();
                    }
                    entries.add(new PieEntry(sellNum[i], listStr.get(i) ));
                }



                PieChart chart = (PieChart) chartFragment.getView().findViewById(R.id.chartFragmentChartView);
                ChartFragment.setPieData(chart,entries);
                ChartFragment.initChart(chart,"销售利润比例图");
            }
            break;
            default:
                break;
        }
    }

    public void onClickScanFragment(View view) {
        int id = view.getId();
        switch (id) {
            //11进货单件，22出货多件
            case R.id.scanFragmentScanInSingleBtn: {
                Intent intent = new Intent(this, CaptureActivity.class);
                intent.setFlags(11);
                startActivityForResult(intent, 11);
            }
            break;
            case R.id.scanFragmentScanInBtn: {
                Intent intent = new Intent(this, CaptureActivity.class);
                intent.setFlags(12);
                startActivityForResult(intent, 12);
            }
            break;
            case R.id.scanFragmentScanOutSingleBtn: {
                Intent intent = new Intent(this, CaptureActivity.class);
                intent.setFlags(21);
                startActivityForResult(intent, 21);
            }
            break;
            case R.id.scanFragmentScanOutBtn: {
                Intent intent = new Intent(this, CaptureActivity.class);
                intent.setFlags(22);
                startActivityForResult(intent, 22);
            }
            break;
            default:
                break;
        }
    }

    public void onClickItemFragment(View view) {
        TextView ID = (TextView) itemFragment.getView().findViewById(R.id.itemFragmentIDTxt);
        String strID = ID.getText().toString();
        int id = view.getId();
        switch (id) {
            case R.id.itemFragmentIconImg: {
                Toast.makeText(this, "暂不支持编辑图片", Toast.LENGTH_SHORT).show();
            }
            break;
            case R.id.itemFragmentNameTxt: {
                Toast.makeText(this, "货物名", Toast.LENGTH_SHORT).show();
                showAlertEditItem(strID, "Name", "货物名");
            }
            break;
            case R.id.itemFragmentTagTxt: {
                Toast.makeText(this, "标签", Toast.LENGTH_SHORT).show();
                showAlertEditItem(strID, "Tag", "标签");
            }
            break;
            case R.id.itemFragmentNumTxt: {
                Toast.makeText(this, "数量", Toast.LENGTH_SHORT).show();
                showAlertEditItem(strID, "Num", "数量");
            }
            break;
/*            case R.id.itemFragmentSellNumTxt: {
                Toast.makeText(this, "本月销售数量", Toast.LENGTH_SHORT).show();
                if (isCurrentMonthOdd()) {
                    showAlertEditItem(strID, "OddSum", "本月销售数量");
                } else {
                    showAlertEditItem(strID, "EvenSum", "本月销售数量");
                }
            }
            break;*/
            case R.id.itemFragmentPriceTxt: {
                Toast.makeText(this, "价格", Toast.LENGTH_SHORT).show();
                showAlertEditItem(strID, "Price", "价格");
            }
            break;
            case R.id.itemFragmentProfitTxt: {
                Toast.makeText(this, "利润", Toast.LENGTH_SHORT).show();
                showAlertEditItem(strID, "Profit", "利润");
            }
            break;
            case R.id.itemFragmentDescriptionTxt: {
                Toast.makeText(this, "描述", Toast.LENGTH_SHORT).show();
                showAlertEditItem(strID, "Description", "描述");
            }
            break;
            default:
                break;
        }
    }

    public void clearBottomColor() {
        mainBtmGoodsImg.setImageResource(R.drawable.goods);
        mainBtmGoodsTxt.setTextColor(ContextCompat.getColor(this, R.color.btm_off));
        mainBtmChartImg.setImageResource(R.drawable.chart);
        mainBtmChartTxt.setTextColor(ContextCompat.getColor(this, R.color.btm_off));
        mainBtmScanImg.setImageResource(R.drawable.scan);
        mainBtmScanTxt.setTextColor(ContextCompat.getColor(this, R.color.btm_off));

    }

    public void showFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.hide(nowFragment);
        transaction.show(fragment);
        nowFragment = fragment;
        transaction.commit();
    }

    public void updateGoodsListView() {
        List<GoodsItem> goodsList;
        goodsList = sqlHelper.getAllGoodsItem();
        GoodsAdapter goodAdapter = new GoodsAdapter(this, goodsList);
        ListView listView = (ListView) findViewById(R.id.goodsFragmentListView);
        listView.setAdapter(goodAdapter);
        setListViewListener(listView);
    }

    public static void updateItemFragment(Fragment fragment, GoodsItem item) {
//      ImageView img =(ImageView) itemFragment.getView().findViewById(R.id.itemFragmentIconImg);
        TextView ID = (TextView) fragment.getView().findViewById(R.id.itemFragmentIDTxt);
        TextView name = (TextView) fragment.getView().findViewById(R.id.itemFragmentNameTxt);
        TextView tag = (TextView) fragment.getView().findViewById(R.id.itemFragmentTagTxt);
        TextView num = (TextView) fragment.getView().findViewById(R.id.itemFragmentNumTxt);
        TextView sellNum = (TextView) fragment.getView().findViewById(R.id.itemFragmentSellNumTxt);
        TextView sellProfit = (TextView) fragment.getView().findViewById(R.id.itemFragmentSellProfitTxt);
        TextView price = (TextView) fragment.getView().findViewById(R.id.itemFragmentPriceTxt);
        TextView profit = (TextView) fragment.getView().findViewById(R.id.itemFragmentProfitTxt);
        TextView description = (TextView) fragment.getView().findViewById(R.id.itemFragmentDescriptionTxt);

//                img
        ID.setText(item.getID());
        name.setText(item.getName());
        tag.setText(item.getTag());
        num.setText(item.getNum() + "");

        int historyNum = getCurrentHistoryNum(item);
        int sellNumInt = historyNum - item.getNum();
        sellNum.setText(sellNumInt + "");

        sellProfit.setText(sellNumInt * item.getProfit() + "");

        price.setText("价格：" + item.getPrice());
        profit.setText("利润：" + item.getProfit());
        description.setText(item.getDescription());
    }

    public void setListViewListener(ListView listView) {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.hide(nowFragment);
                transaction.show(itemFragment);
                nowFragment = itemFragment;
                transaction.commit();
                List<GoodsItem> goodsList;
                goodsList = sqlHelper.getAllGoodsItem();
                GoodsItem item = sqlHelper.getGoodsItemByID(goodsList.get(position).getID());

                updateItemFragment(itemFragment, item);
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                final List<GoodsItem> goodsList;
                goodsList = sqlHelper.getAllGoodsItem();
                String name = sqlHelper.getGoodsItemByID(goodsList.get(position).getID()).getName();
                final View dialogView = getLayoutInflater().inflate(R.layout.main_dialog_delete, null);
                ((TextView) dialogView.findViewById(R.id.deleteItemIDTxt)).setText("名称：" + name);
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setView(dialogView)
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {


                                sqlHelper.deleteGoodsItemByID(goodsList.get(position).getID());

                                updateGoodsListView();

                                Toast.makeText(MainActivity.this, "删除成功！", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                            }
                        });
                builder.create().show();

                return false;
            }
        });
    }

    public void showAlert(String title, String message) {
        new AlertDialog.Builder(this).setTitle(title)
                .setMessage("\n" + message + "\n")
                .setPositiveButton("确定", null).show();
    }

    public void showAlertEditItem(final String itemID, final String columnName, final String hint) {
        final View dialogView = getLayoutInflater().inflate(R.layout.main_dialog_edit, null);
        ((TextView) dialogView.findViewById(R.id.editItemHintTxt)).setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView).
                setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EditText edit = (EditText) dialogView.findViewById(R.id.editItemETxt);
                        try {
                            GoodsItem item = sqlHelper.getGoodsItemByID(itemID);
                            if (columnName.equals("Num")) {
                                int currentNum = item.getNum();
                                Integer eNum = Integer.parseInt(edit.getText().toString());
                                int temp = eNum - currentNum;
                                sqlHelper.updateGoodsItemNumByID(itemID, temp);

                                int historyNum = getCurrentHistoryNum(itemID);
                                int changeNum = historyNum + temp;
                                if (temp > 0) { //只对存入记录
                                    if (isCurrentMonthOdd()) {
                                        sqlHelper.updateGoodsItemByColumn(itemID, "OddSum", changeNum);
                                    } else {
                                        sqlHelper.updateGoodsItemByColumn(itemID, "EvenSum", changeNum);
                                    }
                                }
                            } else if (columnName.equals("Price") || columnName.equals("Profit")) {
                                Float temp = Float.parseFloat(edit.getText().toString());
                                sqlHelper.updateGoodsItemByColumn(itemID, columnName, temp);
                            } else {
                                String temp = edit.getText().toString();
                                sqlHelper.updateGoodsItemByColumn(itemID, columnName, temp);
                            }

                            updateItemFragment(itemFragment, item);
                            Toast.makeText(MainActivity.this, hint + "修改成功！", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, hint + "修改失败！", Toast.LENGTH_SHORT).show();
                        }

                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    }
                });
        builder.create().show();
    }

    public void showAlertScanInWithoutGoods(final String itemID) {
        final View dialogView = getLayoutInflater().inflate(R.layout.main_dialog_add_no, null);
        ((TextView) dialogView.findViewById(R.id.dialogItemIDTxt)).setText("产品号：" + itemID);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        EditText editName = (EditText) dialogView.findViewById(R.id.dialogNameETxt);
                        EditText editNum = (EditText) dialogView.findViewById(R.id.dialogNumETxt);
                        try {
                            String name = editName.getText().toString();
                            int num = Integer.parseInt(editNum.getText().toString());

                            sqlHelper.addGoodsItem(
                                    new GoodsItem(itemID, name, num)
                            );

                            int historyNum = getCurrentHistoryNum(itemID);
                            if (isCurrentMonthOdd()) {
                                sqlHelper.updateGoodsItemByColumn(itemID, "OddSum", historyNum + num);
                            } else {
                                sqlHelper.updateGoodsItemByColumn(itemID, "EvenSum", historyNum + num);
                            }
                            Toast.makeText(MainActivity.this, "货物添加成功！", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, "货物添加失败！", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    }
                });
        builder.create().show();
    }

    public void showAlertScanIn(final String itemID) {
        final View dialogView = getLayoutInflater().inflate(R.layout.main_dialog_add, null);
        ((TextView) dialogView.findViewById(R.id.dialogItemIDTxt)).setText("产品号：" + itemID);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            EditText editNum = (EditText) dialogView.findViewById(R.id.dialogNumETxt);
                            int num = Integer.parseInt(editNum.getText().toString());

                            sqlHelper.updateGoodsItemNumByID(itemID, num);

                            int historyNum = getCurrentHistoryNum(itemID);
                            if (isCurrentMonthOdd()) {
                                sqlHelper.updateGoodsItemByColumn(itemID, "OddSum", historyNum + num);
                            } else {
                                sqlHelper.updateGoodsItemByColumn(itemID, "EvenSum", historyNum + num);
                            }

                            Toast.makeText(MainActivity.this, "货物添加成功！", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, "货物添加失败！", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    }
                });
        builder.create().show();
    }

    public void showAlertScanOut(final String itemID, String name) {
        final View dialogView = getLayoutInflater().inflate(R.layout.main_dialog_minus, null);
        ((TextView) dialogView.findViewById(R.id.dialogItemIDTxt)).setText("产品号：" + itemID);
        ((TextView) dialogView.findViewById(R.id.dialogNameTxt)).setText(name);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            EditText editNum = (EditText) dialogView.findViewById(R.id.dialogNumETxt);
                            int num = Integer.parseInt(editNum.getText().toString());

                            sqlHelper.updateGoodsItemNumByID(itemID, -num);

                            Toast.makeText(MainActivity.this, "出货成功！", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, "出货失败！", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    }
                });
        builder.create().show();
    }

    private int getCurrentHistoryNum(String ID) {
        GoodsItem item = sqlHelper.getGoodsItemByID(ID);
        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH) + 1;// 获取当前月份
        if (month % 2 == 1) {
            return item.getOddSum();
        } else {
            return item.getEvenSum();
        }
    }

    public static int getCurrentHistoryNum(GoodsItem item) {
        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH) + 1;// 获取当前月份
        if (month % 2 == 1) {
            return item.getOddSum();
        } else {
            return item.getEvenSum();
        }
    }

    private boolean isCurrentMonthOdd() {
        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH) + 1;// 获取当前月份
        if (month % 2 == 1) {
            return true;
        } else {
            return false;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Bundle b = intent.getExtras();
        String codedResult_str = b.getString("codedResult");
        switch (resultCode) {
            case 11:
                if (!sqlHelper.isExistItemByID(codedResult_str)) {
                    showAlertScanInWithoutGoods(codedResult_str);
                } else {
                    sqlHelper.updateGoodsItemNumByID(codedResult_str, 1);
                    int historyNum = getCurrentHistoryNum(codedResult_str);
                    if (isCurrentMonthOdd()) {
                        sqlHelper.updateGoodsItemByColumn(codedResult_str, "OddSum", historyNum + 1);
                    } else {
                        sqlHelper.updateGoodsItemByColumn(codedResult_str, "EvenSum", historyNum + 1);
                    }
                }
                break;
            case 12:
                if (!sqlHelper.isExistItemByID(codedResult_str)) {
                    showAlertScanInWithoutGoods(codedResult_str);
                } else {
                    showAlertScanIn(codedResult_str);
                }
                break;
            case 21:
                if (!sqlHelper.isExistItemByID(codedResult_str)) {
                    showAlert("警告", "货物不存在！");
                } else {
                    if (sqlHelper.getGoodsItemByID(codedResult_str).getNum() <= 0) {
                        showAlert("警告", "货物库存为零！");
                    } else {
                        sqlHelper.updateGoodsItemNumByID(codedResult_str, -1);
                    }
                }
                break;
            case 22:
                if (!sqlHelper.isExistItemByID(codedResult_str)) {
                    showAlert("警告", "货物不存在！");
                } else {
                    if (sqlHelper.getGoodsItemByID(codedResult_str).getNum() <= 0) {
                        showAlert("警告", "货物库存为零！");
                    } else {
                        String name = sqlHelper.getGoodsItemByID(codedResult_str).getName();
                        showAlertScanOut(codedResult_str, name);
                    }
                }
                break;
            default:
                break;
        }
    }
}
